<template>
  <onez-view class="onez-frame" v-if="ready" :style="style">
    <onez-view v-for="(item, key) in frames" :key="key" :style="item.style">
      <onez-menu v-if="item.type == 'menu'" :target="target" :menu="item"></onez-menu>
      <onez-frame :info="item" ref="frame" v-else-if="item.type == 'frame'" @event="click"></onez-frame>
    </onez-view>
    <onez-view v-if="box" class="main">
      <onez-view v-if="pagedata">
        <onez-view class="btns top" v-if="pagedata.topBtns.length">
          <onez-button class="bt" v-for="(btn, index) in pagedata.topBtns" :key="index" :type="btn.type" :name="btn.name" @click="click(btn)"></onez-button>
        </onez-view>
        <onez-record :record="pagedata.record" @event="click" v-if="pagedata.record && pagedata.record.length"></onez-record>
        <onez-view class="empty" v-else>
          <onez-view class="text">{{ pagedata.emptyTip || '没有找到符合条件的记录' }}</onez-view>
        </onez-view>
      </onez-view>

      <onez-record :record="record" @event="click" v-if="record && record.length"></onez-record>

      <onez-view class="message" v-if="box.message">{{ box.message }}</onez-view>
      <onez-view class="form" v-if="box.form">
        <onez-view class="form-item" v-for="(item, index) in box.form" :key="index" :class="'form-item-' + item.type">
          <onez-view class="label" v-if="item.label">{{ item.label }}</onez-view>
          <onez-view class="inputBox">
            <onez-view v-if="item.type == 'html'" class="html" :style="item.style">{{ item.value }}</onez-view>
            <onez-input v-else :type="item.type" :placeholder="item.hint" :info="item" v-model="item.value"></onez-input>
          </onez-view>
          <onez-view class="summary" v-if="item.summary">{{ item.summary }}</onez-view>
        </onez-view>
      </onez-view>
      <onez-frame :info="box.frame" @event="click"></onez-frame>
      <onez-view class="btns" v-if="btns.length">
        <template v-for="(btn, index) in btns">
          <template v-if="btn.type == 'text'">
            <onez-view :key="index">{{ btn.name }}</onez-view>
          </template>
          <onez-button v-else class="bt" :key="index" :type="btn.type" :name="btn.name" @click="click(btn)"></onez-button>
        </template>
      </onez-view>
    </onez-view>
  </onez-view>
</template>

<script>
	import onezView from '../onez-view/onez-view.vue'
	import onezButton from '../onez-button/onez-button.vue'
export default {
  name: 'onez-frame',
  components: {
  	onezView, onezButton
  },
  data() {
    return {
      target: 'frame' + (Math.random() + '').split('.')[1],
      ready: false,
      style: '',
      page: 1,
      top_: null,
      pagedata: null,
      box: null,
      formValues: {},
      $get: {},
      btns: [],
      record: [],
      frames: []
    };
  },
  mounted() {
    this.init();
    this.$game.$on('menu-change', this.onMenu);
  },
  destroyed() {
    this.$game.$off('menu-change', this.onMenu);
  },
  props: {
    info: {
      type: Object,
      default: null
    }
  },
  methods: {
    getStyle(item) {
      let style = item.style || '';
      if (item.width) {
        style += 'width:' + item.width + 'px';
      }
      return style;
    },
    loadGet() {
      let gets = {};
      if (this.box && this.box.$page) {
        if (this.box.$page.indexOf('?') != -1) {
          this.box.$page
            .split('?')[1]
            .split('&')
            .forEach(r => {
              var t = r.split('=');
              gets[t[0]] = t[1];
            });
        }
      }
      this.$gets = gets;
      if (gets['target']) {
        this.top_ = gets['target'];
      }
    },
    async getVars() {
      var gets = { userid: this.$game.global.userid, uniIdToken: this.$game.global.userToken };
      if (this.box && this.box.$page) {
        if (this.box.$page.indexOf('?') != -1) {
          this.box.$page
            .split('?')[1]
            .split('&')
            .forEach(r => {
              var t = r.split('=');
              gets[t[0]] = t[1];
            });
        }
      }
      gets.scene = this.$game.scene;
      gets.mypos = this.$game.mypos;
      console.log('!!!!!!!!!!!!!!', gets);
      return gets;
    },
    async formatData($data) {
      if (typeof $data == 'object') {
        let data = JSON.stringify($data);
        let gets = await this.getVars();
        data = data.replace(/\$\{([a-zA-Z0-9_]+)\}/gi, (s, t) => {
          if (typeof gets[t] == 'undefined') {
            return '';
          }
          return gets[t];
        });

        return JSON.parse(data);
      }
      return $data;
    },
    async formatForm(box) {
      if (box.form) {
        if (box.$data) {
          let keys = [];
          box.form.forEach(item => {
            if (item.key) {
              keys.push(item.key);
            }
          });
          let values = await this.$game.call('data', {
            type: 'read',
            token: await this.formatData(box.$data),
            keys: keys.join(',')
          });
          box.form.forEach(item => {
            if (item.key) {
              if (typeof values[item.key] == 'undefined') {
                item.value = item.default || '';
              } else {
                item.value = values[item.key];
              }
            }
            if (item.format) {
              if (item.format == 'date') {
                item.value = this.$game.date(item.args || 'yyyy-MM-dd hh:mm:ss', item.value);
              }
            }
          });
        }
      }
    },
    onInput(item, event) {
      if (item.key) {
        let value = item.value;

        this.formValues[item.key] = value;
      }
    },
    async loadPage(page) {
      this.$game.loading(true);
      let r = await this.$game.call('page', {
        page: page
      });
      let btns = [];
      let pagedata = null;
      if (!r) {
        this.box = { message: '找不到相关信息' };
      } else if (r.error) {
        this.box = { message: r.error };
      } else {
        await this.formatForm(r.data);
        if (r.data.pagedata) {
          //分页显示
          let option = r.data.pagedata.option || {};
          option.page = this.page;
          let record = [];
          let template = JSON.stringify(r.data.pagedata.template);
          let keys = [];
          if (template) {
            template.replace(/\$\{([a-zA-Z0-9_]+)\}/gi, function(s, t) {
              if (keys.indexOf(t) == -1) {
                keys.push(t);
              }
            });
          }
          let vars = await this.getVars();
          let where = null;
          if (r.data.pagedata.where) {
            where = JSON.stringify(r.data.pagedata.where);
            where = where.replace(/\$\{([a-zA-Z0-9_]+)\}/gi, (s, t) => {
              if (typeof vars[t] == 'undefined') {
                return '';
              }
              return vars[t];
            });
            where = JSON.parse(where);
          }

          let T = await this.$game.call('data', {
            type: 'table',
            method: 'page',
            keys: keys,
            table: r.data.pagedata.table,
            where: where || {},
            option: option
          });
          pagedata = {};
          pagedata.topBtns = r.data.topBtns || [];
          T.record.forEach(item => {
            let r = template.replace(/\$\{([a-zA-Z0-9_]+)\}/gi, (s, t) => {
              if (t == 'target') {
                return this.target;
              }
              if (typeof item[t] == 'undefined') {
                return '';
              }
              return item[t];
            });
            r = JSON.parse(r);
            record.push(r);
          });
          pagedata.record = record;
          if (T.pageCount > 1) {
            if (T.page > 1) {
              btns.push({ name: '首页', type: 'primary', token: 'jump', page: 1 });
              btns.push({ name: '上一页', type: 'primary', token: 'jump', page: T.page - 1 });
            }
            btns.push({ name: '第' + T.page + '页', type: 'text' });
            if (T.page < T.pageCount) {
              btns.push({ name: '上一页', type: 'primary', token: 'jump', page: T.page + 1 });
              btns.push({ name: '尾页', type: 'primary', token: 'jump', page: T.pageCount });
            }
          }
        }
        this.box = r.data;
        if (r.data.form && !r.data.nobtn) {
          btns.push({ name: '确定', type: 'primary', token: 'submit' });
          btns.push({ name: '取消', type: 'danger', token: 'cancel' });
        }
      }
      this.btns = btns;
      this.pagedata = pagedata;
      this.loadGet();
      this.$game.loading(false);
      this.$forceUpdate();
    },
    onMenu(e) {
      console.log('~~~~~~~~~~~~~~',e.target,this.target);
      if (e.target && e.target == this.target) {
        if (e.page) {
          this.page = 1;
          if (this.$refs.frame) {
            this.$refs.frame[0].loadPage(e.page);
          } else {
            this.loadPage(e.page);
          }
        }
      }
    },
    async init() {
      if (!this.info) {
        return;
      }
      let style = this.info.style || 'display:block;';
      if (this.info.direction) {
        style += 'flex-direction: ' + this.info.direction + ';';
      }
      if (this.info.frame_width) {
        style += 'width: ' + this.info.frame_width + 'px;';
      }
      if (this.info.frame_height) {
        style += 'height: ' + this.info.frame_height + 'px;';
      }
      this.style = style;

      let frames = [];
      if (this.info.frames) {
        this.info.frames.forEach(item => {
          item.style = this.getStyle(item);
          frames.push(item);
        });
        this.frames = frames;
      }
      if (this.info.page) {
        this.loadPage(this.info.page);
      }
      if (this.info.box) {
        this.box = this.info.box;

        if (this.box.form && !this.box.nobtn) {
          this.btns.push({ name: '确定', type: 'primary', token: 'submit' });
          this.btns.push({ name: '取消', type: 'danger', token: 'cancel' });
          await this.formatForm(this.box);
        }
        if (this.box.record) {
          this.record = this.box.record;
        }
      }
      if (this.info.menuKey) {
        this.$game.menuKey = this.info.menuKey;
      }
      if (this.box && this.box.btns && this.box.btns.length) {
        this.btns = this.box.btns;
      }
      this.loadGet();
      this.$forceUpdate();
      this.ready = true;
    },
    async click(e) {
      if (e.event) {
        if (e.event.page) {
          e.event.page = e.event.page.replace('${target}', this.target);
        }
        this.$game.onEvent(this, e.event);
        return;
      } else if (e.token == 'jump') {
        this.page = e.page;
        let page = this.$game.menuKey.substr(5);
        if (this.$refs.frame) {
          this.$refs.frame[0].loadPage(page);
        } else {
          this.loadPage(page);
        }
      } else if (e.token == 'submit') {
        e.form = this.box.form;
        if (this.box && this.box.$data) {
          this.loadGet();
          let vars = await this.getVars();
          var values = this.formValues || {};
          if (this.box && this.box.$page) {
            if (this.box.$page.indexOf('?') != -1) {
              this.box.$page
                .split('?')[1]
                .split('&')
                .forEach(r => {
                  var t = r.split('=');

                  t[1] = t[1].replace(/\$\{([a-zA-Z0-9_]+)\}/gi, (s, t2) => {
                    if (typeof vars[t2] == 'undefined') {
                      return '';
                    }
                    return vars[t2];
                  });

                  values[t[0]] = t[1];
                });
            }
          }
          for (var i = 0; i < this.box.form.length; i++) {
            var item = this.box.form[i];
            if (item.key) {
              values[item.key] = item.value;
              if (item.notempty && !values[item.key]) {
                this.$game.alert(item.notempty);
                return;
              }
            }
          }
          this.$game.loading(true);
          let r = await this.$game.call('data', {
            type: 'save',
            vars: vars,
            token: await this.formatData(this.box.$data),
            values: values
          });
          let msg = r.msg || this.box.msg;
          if (msg) {
            this.$game.sendMsg(this, msg);
          }

          this.$game.loading(false);
          let goto = r.goto || this.box.goto;
          if (goto) {
            if (this.top_) {
              this.$game.onEvent(this, {
                action: 'menu',
                target: this.top_,
                page: goto
              });
              this.$emit('event', { token: 'close' });
              return;
            }
            this.$game.onEvent(this, {
              action: 'menu',
              target: this.target,
              page: goto
            });
            return;
          }
          let close = r.close || this.box.close;
          if (close) {
            this.$emit('event', { token: 'close' });
          }
          this.$game.parse(r);
          return;
        }
      }
      this.$emit('event', e);
    }
  }
};
</script>

<style scoped>
.btns {
  text-align: center;
  padding: 10px;
}
.btns .bt {
  margin: 0 5px;
}
.message {
  text-align: center;
  padding-top: 30px;
  display: block;
}
.form-item {
  display: flex;
  align-items: center;
  align-content: center;
  padding: 10px;
  white-space: nowrap;
}
.form-item .label {
  min-width: 40px;
  margin-right: 10px;
  display: inline-flex;
}
.form-item .inputBox {
  flex: 1;
  display: inline-flex;
  position: relative;
}
.form-item .summary {
  color: #999;
}

.main {
  flex: 1;
}
.btns.top {
  text-align: left;
  padding: 0;
}
.empty {
  padding: 100px 0;
  text-align: center;
  color: #fff;
}
.html {
  word-wrap: break-word;
  word-break: normal;
  display: block;
}
</style>
